import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/home/subs_list_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../controller/pick/subs_logic.dart';
import '../../../utils/user.dart';
import '../../../widgets/base/qkd_button.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../../expert/items/expert_first_tag.dart';
import '../../expert/items/expert_logo.dart';
import '../../home/qkd_carousel_view.dart';
import '../items/expert_record_tag.dart';

class SubsPage extends StatefulWidget {
  const SubsPage({super.key});

  @override
  State<SubsPage> createState() => _SubsPageState();
}

class _SubsPageState extends State<SubsPage> {
  final logic = Get.put(SubsLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SubsLogic>(builder: (logic) {
      return VisibilityDetector(
        key: const Key("planForm"),
        onVisibilityChanged: (VisibilityInfo info) {
          if (!info.visibleBounds.isEmpty && User.isLogin) {
            logic.getData();
          }
        },
        child: Stack(
          alignment: AlignmentDirectional.topCenter,
          children: [
            Positioned.fill(
              child: Container(
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                          colors: [Colours.white, Colours.greyF2F3F7],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          stops: [0.2, 0.3]))),
            ),
            Image.asset(Utils.getImgPath("nav_head_back.png"),
                width: Get.width, height: Get.width * 128 / 375),
            Column(
              children: [
                Styles.appBar(
                    title: const QkdText("订阅"),
                    backgroundColor: Colours.transparent),
                Container(
                  height: 40,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom:
                              BorderSide(color: Colours.greyEE, width: 0.5))),
                  child: Styles.tabbar(
                      controller: logic.tabController,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      tabs: logic.tabs.map((e) => QkdText(e)).toList(),
                      onTap: (value) => Utils.onEvent("expert_subscribe_tab",
                          params: {"tab": logic.tabs[value]})),
                ),
                Expanded(
                  child: EasyRefresh.builder(
                    controller: logic.refreshController,
                    onRefresh: logic.getRefresh,
                    header: Styles.refreshHeader(
                        clamping: true, position: IndicatorPosition.locator),
                    childBuilder: (context, physics) => ExtendedTabBarView(
                        controller: logic.tabController,
                        children: List.generate(
                            logic.items.length,
                            (index) =>
                                page(logic.items[index], index, physics))),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    });
  }

  Widget page(List<SubsListEntity>? entity, int index, ScrollPhysics physics) {
    return LoadingWidget<bool>(
      isLoading: entity == null,
      data: false,
      child: () => CustomScrollView(
        physics: physics,
        slivers: [
          SliverToBoxAdapter(
            child: QkdCarouselView(
              key: Key("${DateTime.now()}"),
              aspectRatio: 359 / 120,
              radius: 8,
              padding: 8,
              needDot: (logic.lbt ?? []).length > 1,
              carousels: logic.lbt ?? [],
              tapType: "jhd_lbt",
              needTitle: false,
            ).paddingOnly(top: 8),
          ),
          LoadingWidget<bool>(
            isLoading: false,
            data: entity?.length == 0,
            noData: (index == 0 || index == 1) && !User.isLogin
                ? NoDataWidget.sliver(
                    tip: "登录后才能查看",
                    buttonText: "去登录",
                    physics: physics,
                    onTap: () => User.needLogin(() {}))
                : NoDataWidget.sliver(physics: physics),
            child: () => SliverList.list(
                children: entity?.map((e) => _subscribeItem(e)).toList() ?? []),
          ),
          SliverToBoxAdapter(
            child: Container(height: 50),
          )
        ],
      ),
    );
  }

  Widget _subscribeItem(SubsListEntity entity) {
    String? firstTag;
    String? secondTag;
    var tags = entity.tags?.split(",");
    if (tags.hasValue) {
      firstTag = tags![0];
      if (tags.length > 1) secondTag = tags[1];
    }
    return GestureDetector(
      onTap: () {
        Utils.onEvent('expert_subscribe_view',
            params: {'expert_id': entity.expertId});
        Get.toNamed(Routes.userPage,
            arguments: entity.expertId,
            parameters: {"type": "2", "index": "dingyue"});
      },
      child: Block(
          cardStyle: const CardStyle(
              margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 12)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ExpertLogo(
                    logo: entity.logo,
                    planCnt: entity.planCount,
                  ),
                  Container(width: 7),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          QkdText(entity.name ?? '',
                              needCenter: true,
                              fontSize: 15,
                              fontWeight: FontWeight.w500),
                          if (firstTag.hasValue) ...[
                            Container(width: 4),
                            ExpertFirstTag(tag: firstTag!)
                          ]
                        ],
                      ),
                      if (secondTag.hasValue) ...[
                        Container(height: 2),
                        ExpertRecordTag(type: 5, text: secondTag)
                      ]
                    ],
                  ),
                  const Spacer(),
                  _returnRateWidget(entity)
                ],
              ),
              Container(height: 12),
              QkdText(
                entity.info,
                maxLines: 2,
                color: Colours.grey66,
              ).paddingOnly(left: 48, top: 10, bottom: 10),
              Row(
                children: [
                  QkdText(
                    "${entity.subsPrice}"
                    "${entity.subsPrice != "限时免费" ? "/${entity.subsDayTime}" : ""}",
                    color: Colours.main,
                    fontWeight: FontWeight.w500,
                  ).paddingOnly(left: 48),
                  const Spacer(),
                  QkdButton(
                    width: 68,
                    height: 28,
                    onPressed: () {
                      Utils.onEvent('expert_subscribe_subscribe',
                          params: {"expert_id": entity.expertId});
                      Get.toNamed(Routes.subsPay,
                          arguments: entity.expertId,
                          parameters: {"roomId": "${logic.roomId ?? ""}"});
                    },
                    borderRadius: 4,
                    strutStyle: Styles.centerStyle(fontSize: 16),
                    textStyle: const TextStyle(fontSize: 13),
                    backgroundColor: Colours.goldF8D486,
                    foregroundColor: Colours.brown6A3313,
                    text: (entity.subs ?? 0) >= 1 ? "去续订" : "订阅",
                  )
                ],
              )
            ],
          )),
    );
  }

  Widget _returnRateWidget(SubsListEntity entity) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        RichText(
            text: TextSpan(
                style: const TextStyle(
                  color: Colours.main,
                ),
                children: [
              logic.tabIndex != 4
                  ? const WidgetSpan(child: QkdText(''))
                  : const WidgetSpan(
                      baseline: TextBaseline.alphabetic,
                      alignment: PlaceholderAlignment.baseline,
                      child: QkdText("%",
                          fontSize: 9, color: Colours.transparent)),
              WidgetSpan(
                  baseline: TextBaseline.alphabetic,
                  alignment: PlaceholderAlignment.top,
                  child: QkdText(
                      "${logic.tabIndex == 4 ? (entity.hit?.toInt() ?? 0) : (entity.profit?.toInt() ?? 0)}",
                      fontSize: 30,
                      fontFamily: "Din",
                      fontWeight: FontWeight.w700,
                      color: Colours.main,
                      letterSpacing: -2,
                      height: 1)),
              const WidgetSpan(
                  baseline: TextBaseline.alphabetic,
                  alignment: PlaceholderAlignment.baseline,
                  child: QkdText("%", fontSize: 9, color: Colours.main))
            ])),
        QkdText(
          logic.tabIndex == 4
              ? "近${entity.valueM ?? 0}场命中率"
              : "近${entity.profitM ?? 0}场回报",
          color: Colours.main,
          fontSize: 9,
          height: 1,
        )
      ],
    );
  }
}
